package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.Result;
import com.itheima.service.LoginService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("login")
public class LoginController {

    @Reference(version = "1.0")
    LoginService loginService;

    @PostMapping("check")
    public Result check(HttpServletResponse response, @RequestBody Map<String, String> params) {
        String telephone = params.get("telephone");
        String validateCode = params.get("validateCode");
        Result check = loginService.login(telephone, validateCode);
        if (check != null) {
            Cookie cookie = new Cookie("t_ss_a", check.getData().toString());
            cookie.setMaxAge(24 * 3600);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return check;
    }

    @GetMapping("userInfo")
    public Result userInfo(HttpServletRequest request) {
        String token = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if ("t_ss_a".equals(name)) {
                token = cookie.getValue();
            }
        }
        return loginService.userInfo(token);
    }

}
